// 云对象教程: https://uniapp.dcloud.net.cn/uniCloud/cloud-obj
// jsdoc语法提示教程：https://ask.dcloud.net.cn/docs/#//ask.dcloud.net.cn/article/129
// 文件名：deviceController.CloudObject.js

/**
 * DTU开关控制器云对象
 * 用于控制DTU设备的开关状态
 */

// 私有变量
let _clientId = '1e10839ed8f84094bcdf74cb911c53ec';
let _clientSecret = 'de650c0182c749c69eaf74cdf6b90401';
let _username = '17607613066@163.com';
let _password = 'yijiakeji111';
let _apiKey = '1';
let _accessToken = '';
let _refreshToken = '';
let _tokenExpires = 0;
let _baseUrl = 'https://app.dtuip.com';
let _lastError = '';
let _userId = '110517';

/**
 * 获取最后一次错误信息
 * @returns {string} 错误信息
 */
function getLastError() {
    return _lastError;
}

/**
 * HTTP请求封装
 * @param {string} url - 请求URL
 * @param {string} method - 请求方法（GET/POST）
 * @param {Object} [data=null] - 请求数据
 * @param {Object} [headers={}] - 请求头
 * @returns {Promise<Object>} 响应数据
 */
async function _httpRequest(url, method = 'GET', data = null, headers = {}) {
    try {
        const result = await uniCloud.httpclient.request(url, {
            method: method,
            dataType: 'json',
            data: data,
            headers: headers
        });
        
        return result.data;
    } catch (error) {
        _lastError = `请求错误: ${error.message}`;
        throw error;
    }
}

/**
 * 用户登录（获取clientId和secret）
 * @returns {Promise<boolean>} 登录是否成功
 */
async function userLogin() {
    try {
        const url = `${_baseUrl}/api/user/userLogin`;
        const data = {
            userName: _username,
            password: _password,
            apiKey: _apiKey
        };

        const response = await _httpRequest(url, 'POST', data);

        if (response && response.flag === '00') {
            _clientId = response.clientId || _clientId;
            _clientSecret = response.secret || _clientSecret;
            return true;
        }

        _lastError = response?.msg || '登录失败';
        return false;
    } catch (error) {
        _lastError = error.message;
        return false;
    }
}

/**
 * 获取访问令牌
 * @returns {Promise<boolean>} 获取令牌是否成功
 */
async function getAccessToken() {
    try {
        const url = `${_baseUrl}/oauth/token?grant_type=password&username=${encodeURIComponent(_username)}&password=${encodeURIComponent(_password)}`;
        const auth = Buffer.from(`${_clientId}:${_clientSecret}`).toString('base64');
        const headers = {
            'Authorization': `Basic ${auth}`,
            'Content-Type': 'application/x-www-form-urlencoded'
        };

        const response = await _httpRequest(url, 'POST', null, headers);
		uniCloud.logger.info(response+"111111111111111111")
        if (response && response.access_token) {
            _accessToken = response.access_token;
            _refreshToken = response.refresh_token;
            _tokenExpires = Date.now() + (response.expires_in * 1000);
            return true;
        }

        _lastError = response?.error || '获取Token失败';
        return false;
    } catch (error) {
        _lastError = error.message;
        return false;
    }
}

/**
 * 刷新访问令牌
 * @returns {Promise<boolean>} 刷新令牌是否成功
 */
async function refreshAccessToken() {
    try {
        const url = `${_baseUrl}/oauth/token?grant_type=refresh_token&refresh_token=${encodeURIComponent(_refreshToken)}&client_id=${_clientId}&client_secret=${_clientSecret}`;
        const response = await _httpRequest(url, 'POST');

        if (response && response.access_token) {
            _accessToken = response.access_token;
            _refreshToken = response.refresh_token;
            _tokenExpires = Date.now() + (response.expires_in * 1000);
            return true;
        }

        _lastError = response?.error || '刷新Token失败';
        return false;
    } catch (error) {
        _lastError = error.message;
        return false;
    }
}

/**
 * 检查令牌有效性
 * @returns {Promise<boolean>} 令牌是否有效
 */
async function _checkToken() {
    if (!_accessToken || Date.now() >= _tokenExpires - 60000) {
        if (!_refreshToken || !(await refreshAccessToken())) {
            return await getAccessToken();
        }
    }
    return Boolean(_accessToken);
}

/**
 * 设备开关控制（核心方法）
 * @param {string} deviceNo - 设备序列号（如"44L*******D66"）
 * @param {number} sensorId - 传感器ID（如200****95）
 * @param {number} switchValue - 开关状态（0关，1开）
 * @returns {Promise<boolean>} 是否操作成功
 */
async function controlSwitch(deviceNo, sensorId, switchValue) {
    try {
        if (!(await _checkToken())) {
            _lastError = 'Token无效: ' + _lastError;
            return false;
        }

        const url = `${_baseUrl}/api/device/switcherController`;
        const headers = {
            'Content-Type': 'application/json',
            'tlinkAppId': _clientId,
            'Authorization': `Bearer ${_accessToken}`
        };

        const data = {
            userId: _userId,
            deviceNo: deviceNo,
            sensorId: sensorId,
            switcher: parseInt(switchValue)
        };

        const response = await _httpRequest(url, 'POST', data, headers);

        if (response && response.flag) {
            if (response.flag === '00') {
                return true;
            }
            _lastError = response.msg || '开关控制失败';
            return false;
        }

        _lastError = 'API请求失败';
        return false;
    } catch (error) {
        _lastError = error.message;
        return false;
    }
}

/**
 * 控制设备开关的内部方法
 * @param {boolean} [turnOn=true] - 是否开启（true开启，false关闭）
 * @returns {Promise<Object>} 操作结果
 * @returns {boolean} result.success - 是否成功
 * @returns {string} result.message - 结果消息
 */
async function _controlDevice(turnOn = true) {
    // 获取访问令牌
    if (!(await getAccessToken())) {
        return {
            success: false,
            message: '获取Token失败：' + getLastError()
        };
    }

    // 执行开关控制
    const switchValue = turnOn ? 1 : 0;
    if (await controlSwitch('TYNMPSDEOCBYQZWB', 5161195, switchValue)) {
        return {
            success: true,
            message: turnOn ? '设备已开启' : '设备已关闭'
        };
    } else {
        return {
            success: false,
            message: '控制失败：' + getLastError()
        };
    }
}

/**
 * 开启所有开关
 * @returns {Promise<Object>} 操作结果
 * @returns {boolean} result.success - 是否成功
 * @returns {string} result.message - 结果消息
 */
async function turnOnAll() {
    return await _controlDevice(true);
}

/**
 * 关闭所有开关
 * @returns {Promise<Object>} 操作结果
 * @returns {boolean} result.success - 是否成功
 * @returns {string} result.message - 结果消息
 */
async function turnOffAll() {
    return await _controlDevice(false);
}

/**
 * 控制单个开关
 * @param {number} switchNumber - 开关编号（1-8）
 * @param {boolean} [turnOn=true] - 是否开启（true开启，false关闭）
 * @returns {Promise<Object>} 操作结果
 * @returns {boolean} result.success - 是否成功
 * @returns {string} result.message - 结果消息
 */
async function controlSingleSwitch(switchNumber, turnOn = true) {
    if (switchNumber < 1 || switchNumber > 8) {
        return {
            success: false,
            message: '开关编号必须在1-8之间'
        };
    }

    // 获取访问令牌
    if (!(await getAccessToken())) {
        return {
            success: false,
            message: '获取Token失败：' + getLastError()
        };
    }

    // 定义开关对应的传感器ID
    const sensorIds = {
        1: 5263680,
        2: 5263681,
        3: 5263682,
        4: 5263689,
        5: 5263690,
        6: 5263691,
        7: 5263692,
        8: 5263693
    };

    const sensorId = sensorIds[switchNumber];
    const switchValue = turnOn ? 1 : 0;

    if (await controlSwitch('TYNMPSDEOCBYQZWB', sensorId, switchValue)) {
        return {
            success: true,
            message: turnOn ? `开关${switchNumber}已开启` : `开关${switchNumber}已关闭`
        };
    } else {
        return {
            success: false,
            message: '控制失败：' + getLastError()
        };
    }
}

// 导出方法
module.exports = {
    getLastError,
    userLogin,
    getAccessToken,
    refreshAccessToken,
    controlSwitch,
    turnOnAll,
    turnOffAll,
    controlSingleSwitch
};
